package server;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <h1>Class group.</h1> 
 * 
 * Represents a group of the user's friends. A group contains its name and
 * a collection of people who are in this group.
 * It implements the Serializable interface since it is going to be sent
 * through the network.
 * 
 * @author Tomas
 * @date March 4 2009
 */
public class Group implements Serializable{

	/**
	 * Required by the Serializable interface
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Group name
	 */
	protected String groupName = null;
	
	/**
	 * Members of the group. To be implemented as an ArrayList
	 */
	protected List<Person> members = null;
	
	/**
	 * Default constructor. Initializes an empty Group. It is required
	 * by the Serializable interface.
	 */
	public Group(){
		
		members = new ArrayList<Person>();
		
	}
	
	/**
	 * Initializes an instance of the class Group. It gives a name to the group.
	 * 
	 * @param name
	 * 		Name for the group.
	 */
	public Group(String name){
		
		groupName = name;
		members = new ArrayList<Person>();
		
	}
	
	/**
	 * Sets the name of the group.
	 * @param name
	 * 		Name for the group.
	 */
	public void setName(String name){
		
		groupName = name;
		
	}
	
	/**
	 * Obtains the name of the group.
	 * @return
	 * 		Name of the group.
	 */
	public String getName(){
		
		return groupName;
		
	}
	
	/**
	 * Includes a new person in the group.
	 * @param p
	 * 		Person to be included in the group.
	 */
	public void addMember(Person p){
		
		members.add(p);
		
	}
	
	/**
	 * Removes a member from the group.
	 * @param p
	 * 		Person to be removed.
	 * @return
	 * 		Boolean value telling if the operation was successful or not.
	 */
	public boolean removeMember(Person p){
		
		if(members.contains(p)){
			members.remove(p);
			return true;
		}else{
			return false;
		}
		
	}
	
	/**
	 * Obtains an iterator through the collection of members in the group.
	 * @return
	 * 		Iterator over the members in the group.
	 */
	public Iterator<Person> getMembers(){
		
		return members.iterator();
		
	}
	
	/**
	 * Finds a person in the group
	 * 
	 * @param name
	 * 		Person's name.
	 * @return
	 * 		Person, or null if there is no such person.
	 */
	public Person findPerson(String name){
		
		for(int i = 0; i < members.size(); i++){
			if(members.get(i).getUsername().equals(name)){
				return members.get(i);
			}
		}
		
		return null;
		
	}
}
